package com.yxq.mdt.app.modules.personal.ui.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.ToastUtils;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.orhanobut.hawk.Hawk;
import com.wuhenzhizao.titlebar.widget.CommonTitleBar;
import com.yxq.mdt.app.R;
import com.yxq.mdt.app.base.BaseActivity;
import com.yxq.mdt.app.constant.Constant;
import com.yxq.mdt.app.constant.SPKey;
import com.yxq.mdt.app.glide.GlideHelper;
import com.yxq.mdt.app.modules.bean.UploadImageBean;
import com.yxq.mdt.app.modules.bottomsheet.PersonalAgeSheetDialogFragment;
import com.yxq.mdt.app.modules.bottomsheet.PersonalLikeTypeSheetDialogFragment;
import com.yxq.mdt.app.modules.bottomsheet.PersonalLoveSheetDialogFragment;
import com.yxq.mdt.app.modules.bottomsheet.PersonalPersonalityTagsSheetDialogFragment;
import com.yxq.mdt.app.modules.bottomsheet.PersonalPurposeSheetDialogFragment;
import com.yxq.mdt.app.modules.bottomsheet.PersonalSexSheetDialogFragment;
import com.yxq.mdt.app.modules.bottomsheet.PersonalSexualSheetDialogFragment;
import com.yxq.mdt.app.modules.bottomsheet.SoundVoiceBottomSheetDialogFragment;
import com.yxq.mdt.app.modules.personal.bean.AddressBean;
import com.yxq.mdt.app.modules.personal.bean.EditPicutreResultBean;
import com.yxq.mdt.app.modules.personal.bean.MyPersonalBean;
import com.yxq.mdt.app.modules.personal.bean.UpdateAttributeRequestBean;
import com.yxq.mdt.app.modules.personal.model.MainPersonalModel;
import com.yxq.mdt.app.modules.personal.model.UserModel;
import com.yxq.mdt.app.modules.personal.presenter.IUserContract;
import com.yxq.mdt.app.modules.personal.presenter.UserPresenter;
import com.yxq.mdt.app.modules.picturebrowse.ui.PictureActivity;
import com.yxq.mdt.app.modules.socialcontact.adapter.PublishEditListAdapter;
import com.yxq.mdt.app.modules.socialcontact.bean.SocialPersonalHomepageBean;
import com.yxq.mdt.app.modules.socialcontact.model.MainSocialContactModel;
import com.yxq.mdt.app.net.ApiModel;
import com.yxq.mdt.app.utils.EmojiFilter;
import com.yxq.mdt.app.utils.GlideEngine;
import com.yxq.mdt.app.utils.GridSpacingItemDecoration;
import com.yxq.mdt.app.utils.MediaPlayerHelper;
import com.yxq.mdt.app.utils.MediaRecorderHelper;
import com.yxq.mdt.app.utils.StringUtils;
import com.yxq.mdt.app.widgets.CheckAudioPermission;
import com.yxq.mdt.app.widgets.CircleImageView;
import com.yxq.mdt.app.widgets.CustomAddressPicker;
import com.yxq.mdt.app.widgets.OssHelper;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.jzvd.Jzvd;
import cn.qqtheme.framework.entity.City;
import cn.qqtheme.framework.entity.County;
import cn.qqtheme.framework.entity.Province;
import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * 个人资料编辑
 */
public class MainPersonalEditData extends BaseActivity<UserPresenter> implements IUserContract.View {
    @BindView(R.id.titlebar)
    CommonTitleBar titlebar;
    @BindView(R.id.personal_edit_picture)
    CircleImageView personalEditPicture;
    @BindView(R.id.personal_add_voice)
    TextView personalAddVoice;
    @BindView(R.id.personal_add_personalized)
    EditText personalAddPersonalized;
    @BindView(R.id.personal_add_nike_name)
    EditText personalAddNikeName;
    @BindView(R.id.personal_add_sex)
    TextView personalAddSex;
    @BindView(R.id.personal_add_age)
    TextView personalAddAge;
    @BindView(R.id.personal_add_marriage)
    TextView personalAddMarriage;
    @BindView(R.id.personal_add_sexual_preference)
    TextView personalAddSexualPreference;
    @BindView(R.id.personal_add_purpose)
    TextView personalAddPurpose;
    @BindView(R.id.personal_add_address)
    TextView personalAddAddress;
    @BindView(R.id.personal_add_home_address)
    TextView personalAddHomeAddress;
    @BindView(R.id.personal_add_tally)
    TextView personalAddTally;
    @BindView(R.id.personal_add_like_type)
    TextView personalAddLikeType;
    @BindView(R.id.personal_btn_send)
    TextView personalBtnSend;
    //选择年龄
    PersonalAgeSheetDialogFragment personalAgeSheetDialogFragment;
    //选择喜欢类型
    PersonalLikeTypeSheetDialogFragment personalLikeTypeSheetDialogFragment;
    //选择婚恋状况
    PersonalLoveSheetDialogFragment personalLoveSheetDialogFragment;
    //选择性取向
    PersonalSexualSheetDialogFragment personalSexualSheetDialogFragment;
    //交友意向
    PersonalPurposeSheetDialogFragment personalPurposeSheetDialogFragment;
    //录音弹窗
    SoundVoiceBottomSheetDialogFragment soundVoiceBottomSheetDialogFragment;
    //选择性别
    PersonalSexSheetDialogFragment personalSexSheetDialogFragment;
    ArrayList<Province> provinceArrayList = new ArrayList<>();
    @BindView(R.id.main_personal_note)
    ImageView mainPersonalNote;
    @BindView(R.id.main_personal_add_voice_time)
    TextView mainPersonalAddVoiceTime;
    @BindView(R.id.main_personal_start_play)
    RelativeLayout mainPersonalStartPlay;
    @BindView(R.id.publish_del_voice)
    ImageView publishDelVoice;
    @BindView(R.id.main_personal_save_voice)
    LinearLayout mainPersonalSaveVoice;
    @BindView(R.id.personal_img_recyclerView)
    RecyclerView personalImgRecyclerView;
    private boolean hideProvince = false;
    private boolean hideCounty = true;
    private String selectedProvince = "", selectedCity = "", selectedCounty = "";
    String selectedProvinceId = "", selectedCityId = "", selectedCountyId = "";
    private String selectedProvinceHome = "", selectedCityHome = "", selectedCountyHome = "";
    String selectedProvinceIdHome = "", selectedCityIdHome = "", selectedCountyIdHome = "";
    private MediaRecorderHelper mMediaRecorderHelper;
    private String playTime, playPath;
    private int audioId = -1;
    CountDownTimer countDownTimer;
    PublishEditListAdapter publishEditListAdapter;
    List<UploadImageBean> uploadImageBeanList;
    List<LocalMedia> images;
    String avatar = null;
    int len = 0;
    List<String> imageList;
    int sex;
    int age;
    String birthday;
    String constellation;
    int birthdayShow;
    String marriage;
    int marriageShow;
    String sexual;
    int sexualShow;
    String friendsIntention;
    String residence;
    String residenceCode;
    String hometown;
    String hometownCode;
    String loveType;
    String userProfile;

    @Override
    public int getLayoutId() {
        return R.layout.activity_main_personal_edit_data;
    }

    @Override
    public void initView() {
        imageList = new ArrayList<>();
        //初始化图片上传控件
        personalImgRecyclerView.setLayoutManager(new GridLayoutManager(this, 4));
        uploadImageBeanList = new ArrayList<>();
        uploadImageBeanList.add(new UploadImageBean());
        publishEditListAdapter = new PublishEditListAdapter(uploadImageBeanList);
        personalImgRecyclerView.setAdapter(publishEditListAdapter);
        personalImgRecyclerView.addItemDecoration(new GridSpacingItemDecoration(4, 4, false));
        publishEditListAdapter.setOnItemClickListener((adapter, view, position) -> {

            if (publishEditListAdapter.getItem(position).getItemType() == -1) {
                //选择图片
                selectImages();
            } else {
                //预览网络图片
                if (publishEditListAdapter.getData() != null && publishEditListAdapter.getData().size() > 0) {
                    Intent intent = new Intent(mActivity, PictureActivity.class);
                    intent.putExtra("position", position);
                    ArrayList<String> images = new ArrayList<>();
                    for (UploadImageBean uploadImageBean : publishEditListAdapter.getData()) {
                        if (uploadImageBean.getItemType() != -1) {
                            images.add(uploadImageBean.getPath());
                        }
                    }
                    intent.putExtra("images", images);
                    startActivity(intent);
                }
                //预览本地图片
//                PictureSelector.create(mActivity).externalPicturePreview(position, images);
            }
        });

        publishEditListAdapter.setOnItemChildClickListener((adapter, view, position) -> {

            List<UploadImageBean> uploadImageBeanList = publishEditListAdapter.getData();

            if (uploadImageBeanList.get(uploadImageBeanList.size() - 1).getItemType() != -1) {
                //删除最后一张图片
                uploadImageBeanList.remove(position);

                //第一张不是添加图片，添加按钮
                List<UploadImageBean> temp = new ArrayList<>();
                temp.addAll(uploadImageBeanList);
                temp.add(new UploadImageBean());
                //添加新数据
                publishEditListAdapter.setNewData(temp);
            } else {
                //删除
                publishEditListAdapter.remove(position);
            }
            //更新封面接口
            updateAttribute(publishEditListAdapter.getData());
        });
        mMediaRecorderHelper = new MediaRecorderHelper(getRecorderFilePath());
        //删除当前的录音并重新录制
        publishDelVoice.setOnClickListener(view -> {
            mMediaRecorderHelper.cancel();
            mainPersonalSaveVoice.setVisibility(View.GONE);
            personalAddVoice.setVisibility(View.VISIBLE);
        });
        personalAddVoice.setOnClickListener(view -> {
            //检测是否有录音权限
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO)
                    != PackageManager.PERMISSION_GRANTED) {
                Log.i(TAG, "默认无录音权限");
                if (Build.VERSION.SDK_INT >= 23) {
                    requestPermissions(new String[]{Manifest.permission.RECORD_AUDIO}, 1001);
                }
            } else {
                if (mMediaRecorderHelper.getCurrentFilePath() != null) {
                    File file = new File(mMediaRecorderHelper.getCurrentFilePath());
                    file.delete();
                } else {
                    soundVoiceBottomSheetDialogFragment = new SoundVoiceBottomSheetDialogFragment("s");
                    soundVoiceBottomSheetDialogFragment.show(getSupportFragmentManager(), "soundVoiceBottomSheetDialogFragment");
                    soundVoiceBottomSheetDialogFragment.setSoundVoiceBottomSheetDialogFragmentTime((time, path) -> {//返回的时间和所在路径.
                        if (TextUtils.isEmpty(time)) {
                            mainPersonalAddVoiceTime.setText("");
                        } else {
                            mainPersonalAddVoiceTime.setText(time + "″");
                            playPath = path;
                            playTime = time;
                            Log.e("path", path);
                            personalAddVoice.setVisibility(View.GONE);
                            mainPersonalSaveVoice.setVisibility(View.VISIBLE);
                            uploadAudio(playPath);
                        }
                    });
                }
            }
        });
        mainPersonalStartPlay.setOnClickListener(view -> {
            MediaPlayerHelper.playSound(playPath);
            getTime(playTime, null, mainPersonalAddVoiceTime);
            countDownTimer.start();
        });

        personalAddNikeName.setFilters(new InputFilter.LengthFilter[]{new EmojiFilter(13)});
        personalAddPersonalized.setFilters(new InputFilter.LengthFilter[]{new EmojiFilter(15)});
    }

    //打开图片选择器
    private void selectImages() {
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .loadImageEngine(GlideEngine.createGlideEngine())
                .maxSelectNum(9 - publishEditListAdapter.getData().size())//最大选择数目 最大6张减去现在已经添加的张数
                .compress(true)
                .minSelectNum(1)
                .imageSpanCount(4)
                .selectionMode(PictureConfig.MULTIPLE)
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }

    //上传头像
    private void selectHeadImages() {
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .loadImageEngine(GlideEngine.createGlideEngine())
                .maxSelectNum(1)//最大选择数目 最大6张减去现在已经添加的张数
                .compress(true)
                .minSelectNum(1)
                .imageSpanCount(4)
                .selectionMode(PictureConfig.SINGLE)
                .forResult(PictureConfig.REQUEST_CAMERA);
    }

    //录音地址管理
    public String getRecorderFilePath() {
        String path = "";
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            path = getExternalCacheDir().getAbsolutePath();
        } else {
            path = getCacheDir().getAbsolutePath();

        }
        return path + File.separator + "Recorder";
    }


    /**
     * @param playTime  开始时间
     * @param imageView 获取当前控件
     * @param timeTv    获取显示秒数
     */
    private void getTime(String playTime, ImageView imageView, TextView timeTv) {
        if (imageView != null) {
            imageView.setImageResource(R.mipmap.voice_note_new);
        }
        countDownTimer = new CountDownTimer(Integer.parseInt(playTime) * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                timeTv.setText(millisUntilFinished / 1000 + "″");
            }

            @Override
            public void onFinish() {
                timeTv.setText(Integer.parseInt(playTime) + "″");
                if (imageView != null) {
                    imageView.setImageResource(R.mipmap.voice_note);
                }
                countDownTimer.cancel();
            }
        };
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        //加载缓存的区域数据
        List<AddressBean> addressBeanList = null;
        String address = Hawk.get("addressList", null);
        if (address != null) {
            addressBeanList = JSON.parseArray(address, AddressBean.class);
        }
        if (addressBeanList != null) {
            parseAddressList(addressBeanList);
        }
        mPresenter = new UserPresenter(this, new UserModel());
        MainPersonalModel.getPersonalDate(Constant.getLbsUserToken(), new ApiModel.CommonCallback<MyPersonalBean>() {
            @Override
            public void onSuccess(MyPersonalBean myPersonalBean) {
                if (myPersonalBean == null) {
                    return;
                }
                Hawk.put(SPKey.SP_KEY_USER_MY_INFO, myPersonalBean);
                initUserInfo();
            }

            @Override
            public void onError(String errMsg) {

            }
        });

    }

    private MyPersonalBean getUserInfo() {
        MyPersonalBean p = Hawk.get(SPKey.SP_KEY_USER_MY_INFO);
        return p;
    }

    private void initUserInfo() {
        MyPersonalBean p = Hawk.get(SPKey.SP_KEY_USER_MY_INFO);
        //头像
        GlideHelper.setLoadImage(mActivity, p.getHeadimg(), R.mipmap.head_icon, personalEditPicture);
        //昵称
        personalAddNikeName.setText(p.getGsName() + "");
//        personalAddNikeName.addTextChangedListener(new TextWatcher() {
//            @Override
//            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
//
//            }
//
//            @Override
//            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
//
//            }
//
//            @Override
//            public void afterTextChanged(Editable editable) {
//                String content = personalAddNikeName.getText().toString().trim();
//                if (content.length() == 8) {
//                    showBottomToast("最多可输入八个文字!");
//                }
//            }
//        });
        //性别
        sex = p.getSex();
        if (sex == 1) {
            personalAddSex.setText("男");
        } else if (sex == 2) {
            personalAddSex.setText("女");
        }
        //个性签名
        personalAddPersonalized.setText(p.getGeneration());
        birthday = p.getBirthday();
        if (birthday != null && birthday.length() > 3) {
            int year = Integer.parseInt(birthday.substring(0, birthday.indexOf("-")));
            age = Calendar.getInstance().get(Calendar.YEAR) - year;
            //年龄
            personalAddAge.setText(age + "");
        }
        constellation = p.getConstellation();
        birthdayShow = p.getBirthdayShow();
        //婚恋
        personalAddMarriage.setText(p.getMarriage());
        marriage = p.getMarriage();
        marriageShow = p.getMarriageShow();
        //性取向
        personalAddSexualPreference.setText(p.getSexual());
        sexual = p.getSexual();
        sexualShow = p.getSexualShow();
        //交友意向
        personalAddPurpose.setText(p.getFriendsIntention());
        friendsIntention = p.getFriendsIntention();
        //所在地
        personalAddAddress.setText(p.getResidence());
        residence = p.getResidence();
        residenceCode = p.getResidenceCode();
        if (residence != null && residence.split(";") != null && residence.split(";").length >= 2) {
            selectedProvince = residence.split(";")[0];
            selectedCity = residence.split(";")[1];
        }
        //家乡
        personalAddHomeAddress.setText(p.getHometown());
        hometown = p.getHometown();
        hometownCode = p.getHometownCode();
        if (hometown != null && hometown.split(";") != null && hometown.split(";").length >= 2) {
            selectedProvinceHome = hometown.split(";")[0];
            selectedCityHome = hometown.split(";")[1];
        }
        //个性标签
        personalAddTally.setText(p.getUserProfile());
        userProfile = p.getUserProfile();
        //喜欢类型
        personalAddLikeType.setText(p.getLoveType());
        loveType = p.getLoveType();

        //封面图
        if (p.getIntroductionImgFile() != null && p.getIntroductionImgFile().size() > 0) {
            List<UploadImageBean> data = new ArrayList<>();
            UploadImageBean uploadImageBean;
            for (MyPersonalBean.IntroductionImgFileBean imgFileBean : p.getIntroductionImgFile()) {
                uploadImageBean = new UploadImageBean();
                uploadImageBean.setItemType(0);
                uploadImageBean.setPath(imgFileBean.getFilePath());
                data.add(uploadImageBean);
            }
            List<UploadImageBean> temp = publishEditListAdapter.getData();
            temp.remove(temp.size() - 1);
            temp.addAll(data);
            temp.add(new UploadImageBean());
            publishEditListAdapter.setNewData(temp);

            if (publishEditListAdapter.getData().size() == 9) {
                publishEditListAdapter.getData().remove(8);
            }
            publishEditListAdapter.notifyDataSetChanged();
        }

        //语音
        if (p.getIntroductionAudioFile() != null && p.getIntroductionAudioFile().size() > 0) {
            playTime = StringUtils.getMediaDuration(p.getIntroductionAudioFile().get(0).getFilePath()) + "";
            audioId = p.getIntroductionAudioFile().get(0).getId();
            mainPersonalAddVoiceTime.setText(playTime + "″");
            playPath = p.getIntroductionAudioFile().get(0).getFilePath();
            Log.e("path", playPath);
            personalAddVoice.setVisibility(View.GONE);
            mainPersonalSaveVoice.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 处理地区数据
     *
     * @param addressBeanList
     */
    private void parseAddressList(List<AddressBean> addressBeanList) {
        for (AddressBean addressBean : addressBeanList) {
            Province province = new Province(addressBean.getId() + "", addressBean.getName());
            List<AddressBean.ListBeanX> listBeanXES = addressBean.getList();
            List<City> cityList = new ArrayList<>();
            for (AddressBean.ListBeanX cityBean : listBeanXES) {
                City city = new City(cityBean.getId() + "", cityBean.getName());
                List<AddressBean.ListBeanX.ListBean> listBeanList = cityBean.getList();
                List<County> countyList = new ArrayList<>();
                for (AddressBean.ListBeanX.ListBean CountyBean : listBeanList) {
                    countyList.add(new County(CountyBean.getId() + "", CountyBean.getName()));
                }
                city.setCounties(countyList);
                cityList.add(city);
            }
            province.setCities(cityList);
            provinceArrayList.add(province);
        }
    }

    @OnClick({R.id.personal_edit_picture, R.id.personal_add_voice, R.id.personal_add_sex, R.id.personal_add_age, R.id.personal_add_marriage, R.id.personal_add_sexual_preference, R.id.personal_add_purpose, R.id.personal_add_address, R.id.personal_add_home_address, R.id.personal_add_tally, R.id.personal_add_like_type, R.id.personal_btn_send})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            //修改头像
            case R.id.personal_edit_picture:
                selectHeadImages();
                break;
            //性别
            case R.id.personal_add_sex:
                personalSexSheetDialogFragment = new PersonalSexSheetDialogFragment(sex);
                personalSexSheetDialogFragment.show(getSupportFragmentManager(), "personalSexSheetDialogFragment");
                personalSexSheetDialogFragment.setPersonalSexSheetDialogFragmentInterface(new PersonalSexSheetDialogFragment.PersonalSexSheetDialogFragmentInterface() {
                    @Override
                    public void checked(int s) {
                        sex = s;
                        personalAddSex.setText(sex == 1 ? "男" : "女");
                    }
                });
                break;
            //年龄
            case R.id.personal_add_age:
                personalAgeSheetDialogFragment = new PersonalAgeSheetDialogFragment(birthday, birthdayShow);
                personalAgeSheetDialogFragment.show(getSupportFragmentManager(), "personalAgeSheetDialogFragment");
                personalAgeSheetDialogFragment.setPersonalAgeSheetDialogFragmentInterface(new PersonalAgeSheetDialogFragment.PersonalAgeSheetDialogFragmentInterface() {
                    @Override
                    public void date(String _date, int _age, String _constellation, boolean _confidentiality) {
                        personalAddAge.setText(_age + "");
                        birthday = _date;
                        age = _age;
                        constellation = _constellation;
                        birthdayShow = _confidentiality ? 1 : 0;
                    }
                });
                break;
            //婚恋
            case R.id.personal_add_marriage:
                personalLoveSheetDialogFragment = new PersonalLoveSheetDialogFragment(marriage, marriageShow);
                personalLoveSheetDialogFragment.show(getSupportFragmentManager(), "personalLoveSheetDialogFragment");
                personalLoveSheetDialogFragment.setPersonalLoveSheetDialogFragmentInterface(new PersonalLoveSheetDialogFragment.PersonalLoveSheetDialogFragmentInterface() {
                    @Override
                    public void checked(int index, String data, boolean confidentiality) {
                        personalAddMarriage.setText(data);
                        marriage = data;
                        marriageShow = confidentiality ? 1 : 0;
                    }
                });
                break;
            //性取向
            case R.id.personal_add_sexual_preference:
                personalSexualSheetDialogFragment = new PersonalSexualSheetDialogFragment(sexual, sexualShow);
                personalSexualSheetDialogFragment.show(getSupportFragmentManager(), "personalSexualSheetDialogFragment");
                personalSexualSheetDialogFragment.setPersonalSexualSheetDialogFragmentInterface(new PersonalSexualSheetDialogFragment.PersonalSexualSheetDialogFragmentInterface() {
                    @Override
                    public void checked(int index, String data, boolean confidentiality) {
                        personalAddSexualPreference.setText(data);
                        sexual = data;
                        sexualShow = confidentiality ? 1 : 0;
                    }
                });
                break;
            //交友意向
            case R.id.personal_add_purpose:
                personalPurposeSheetDialogFragment = new PersonalPurposeSheetDialogFragment(friendsIntention);
                personalPurposeSheetDialogFragment.show(getSupportFragmentManager(), "personalPurposeSheetDialogFragment");
                personalPurposeSheetDialogFragment.setPersonalPurposeSheetDialogFragmentInterface(new PersonalPurposeSheetDialogFragment.PersonalPurposeSheetDialogFragmentInterface() {
                    @Override
                    public void checked(int index, String data) {
                        personalAddPurpose.setText(data);
                        friendsIntention = data;
                    }
                });
                break;
            //所在地
            case R.id.personal_add_address:
                addressPickView(1);
                break;
            //家乡
            case R.id.personal_add_home_address:
                addressPickView(2);
                break;
            //个性标签
            case R.id.personal_add_tally:
                PersonalPersonalityTagsSheetDialogFragment personalPersonalityTagsSheetDialogFragment = new PersonalPersonalityTagsSheetDialogFragment(userProfile);
                personalPersonalityTagsSheetDialogFragment.show(getSupportFragmentManager(), "PersonalPersonalityTagsSheetDialogFragment");
                personalPersonalityTagsSheetDialogFragment.setPersonalPersonalityTagsSheetDialogFragmentInterface(new PersonalPersonalityTagsSheetDialogFragment.PersonalPersonalityTagsSheetDialogFragmentInterface() {
                    @Override
                    public void checked(HashMap<String, String> data) {
                        if (data.size() > 0) {
                            StringBuffer buffer = new StringBuffer();
                            Collection<String> list = data.values();
                            int i = 0;
                            for (String s : list) {
                                buffer.append(s);
                                if (i != list.size() - 1) {
                                    buffer.append(",");
                                }
                                i++;
                            }
                            userProfile = buffer.toString();
                            personalAddTally.setText(userProfile);
                        }
                    }
                });
                break;
            //喜欢类型
            case R.id.personal_add_like_type:
                personalLikeTypeSheetDialogFragment = new PersonalLikeTypeSheetDialogFragment(loveType);
                personalLikeTypeSheetDialogFragment.show(getSupportFragmentManager(), "personalLikeTypeSheetDialogFragment");
                personalLikeTypeSheetDialogFragment.setPersonalLikeTypeSheetDialogFragmentInterface(new PersonalLikeTypeSheetDialogFragment.PersonalLikeTypeSheetDialogFragmentInterface() {
                    @Override
                    public void checked(HashMap<String, String> data) {

                        if (data.size() > 0) {
                            StringBuffer buffer = new StringBuffer();
                            Collection<String> list = data.values();
                            int i = 0;
                            for (String s : list) {
                                buffer.append(s);
                                if (i != list.size() - 1) {
                                    buffer.append(",");
                                }
                                i++;
                            }
                            loveType = buffer.toString();
                            personalAddLikeType.setText(loveType);
                        }
                    }
                });
                break;
            //确定提交
            case R.id.personal_btn_send:
                submit();
                break;
        }
    }

    /**
     * 提交保存
     */
    private void submit() {
        //判断是否更新头像 有更新需要先上传头像
        if (avatar != null) {
            uploadAvatar(avatar);
        } else {
            saveData(null);
        }
    }

    private void addressPickView(int type) {
        if (provinceArrayList.size() == 0) {
            showLoadingDialog();
            return;
        }
        CustomAddressPicker picker = new CustomAddressPicker(this, provinceArrayList);
        /** 显示几列 **/
        picker.setHideProvince(hideProvince);
        picker.setHideCounty(hideCounty);

        /** 标题区域 **/
        picker.setTopBackgroundColor(getResources().getColor(R.color.white));//设置标题背景颜色
        picker.setTopHeight(60);//设置顶部标题栏高度（单位为dp）

        picker.setCancelText("取消");
        picker.setCancelTextSize(14);
        picker.setCancelTextColor(getResources().getColor(R.color.color_font_black));//设置顶部标题栏取消按钮文字颜色
        picker.setCancelVisible(true);//设置左边按钮是否显示

        picker.setTitleText("所在地区");//标题栏
        picker.setTitleTextSize(14);//标题栏大小
        picker.setTitleTextColor(getResources().getColor(R.color.color_font_black));//设置所在区域颜色

        picker.setSubmitText("完成");//设置标题右边文字
        picker.setSubmitTextSize(14);//设置完成按钮大小
        picker.setSubmitTextColor(getResources().getColor(R.color.color_font_black));//设置完成按钮颜色

        /**  标题与列表的分割线 **/
        picker.setTopLineColor(getResources().getColor(R.color.white));
        picker.setTopLineVisible(true);
        picker.setTopLineHeight(10);

        /** 列表区域 **/
        picker.setTextSize(14);//字体大小
        picker.setTextColor(getResources().getColor(R.color.black));//设置省市县字体滚动颜色
        picker.setDividerColor(getResources().getColor(R.color.white));//设置分割线的颜色
        picker.setLineSpaceMultiplier(4);
        /** 弹框消失的设置 **/
        picker.setCancelable(true);//false：必须选择后弹框才消失，true：点击框外可弹框消失


        /** 列的比重 **/
        if (hideCounty) {
            picker.setColumnWeight(0.8f, 1.0f);
        } else if (hideProvince) {
            picker.setColumnWeight(1.0f, 0.8f);
        } else {
            picker.setColumnWeight(1.0f, 1.0f, 1.0f);
        }
        switch (type) {
            case 1:
                picker.setSelectedItem(selectedProvince, selectedCity, selectedCounty);//设置默认
                break;
            case 2:
                picker.setSelectedItem(selectedProvinceHome, selectedCityHome, selectedCountyHome);//设置默认
                break;
        }
        picker.setOnAddressPickListener((Province province, City city, County county) -> {

            switch (type) {
                case 1:
                    selectedProvinceId = province.getAreaId();
                    selectedCityId = city.getAreaId();
                    selectedProvince = province.getAreaName();
                    selectedCity = city.getAreaName();
                    personalAddAddress.setText(String.format("%s %s", province.getAreaName(), city.getAreaName()));
                    residence = String.format("%s;%s", province.getAreaName(), city.getAreaName());
                    residenceCode = String.format("%s;%s", selectedProvinceId, selectedCityId);
                    break;
                case 2:
                    selectedProvinceIdHome = province.getAreaId();
                    selectedCityIdHome = city.getAreaId();
                    selectedProvinceHome = province.getAreaName();
                    selectedCityHome = city.getAreaName();
                    personalAddHomeAddress.setText(String.format("%s %s", province.getAreaName(), city.getAreaName()));
                    hometown = String.format("%s;%s", province.getAreaName(), city.getAreaName());
                    hometownCode = String.format("%s;%s", selectedProvinceIdHome, selectedCityIdHome);
                    break;
            }
        });
        picker.show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (countDownTimer != null) {
            countDownTimer.onFinish();
        }
        Jzvd.releaseAllVideos();
        MediaPlayerHelper.realese();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                //封面返回图片集
                case PictureConfig.CHOOSE_REQUEST:
                    //compressPath 压缩图片地址
                    // 图片选择结果回调
                    images = PictureSelector.obtainMultipleResult(data);
                    parseLocalMedia(images);
                    if (images != null && images.size() > 0) {
                        imageList.clear();
                        uploadPictures();
                    }
                    break;
                //头像返回图片
                case PictureConfig.REQUEST_CAMERA:
                    List<LocalMedia> images = PictureSelector.obtainMultipleResult(data);
                    LocalMedia media = images.get(0);
                    GlideHelper.setLoadImage(mActivity, media.getCompressPath(), R.mipmap.head_icon, personalEditPicture);
                    avatar = media.getCompressPath();
                    break;
                default:
                    throw new IllegalStateException("Unexpected value: " + requestCode);
            }
        }
        super.onActivityResult(requestCode, resultCode, data);

    }

    /**
     * 封面图片
     *
     * @param images
     */
    private void parseLocalMedia(List<LocalMedia> images) {
        List<UploadImageBean> data = new ArrayList<>();
        UploadImageBean uploadImageBean;
        for (LocalMedia localMedia : images) {
            uploadImageBean = new UploadImageBean();
            uploadImageBean.setItemType(0);
            uploadImageBean.setPath(localMedia.getCompressPath());
            data.add(uploadImageBean);
        }
        List<UploadImageBean> temp = publishEditListAdapter.getData();
        temp.remove(temp.size() - 1);
        temp.addAll(data);
        temp.add(new UploadImageBean());
        publishEditListAdapter.setNewData(temp);

        if (publishEditListAdapter.getData().size() == 9) {
            publishEditListAdapter.getData().remove(8);
        }
        publishEditListAdapter.notifyDataSetChanged();
    }

    @Override
    public void onSaveSuccess(String data) {
        hideLoadingDialog();
        ToastUtils.showShort("更新成功");
        String userId = getIntent().getStringExtra("userId");
        MainSocialContactModel.getGaUserExtVoById(userId, new ApiModel.CommonCallback<SocialPersonalHomepageBean>() {
            @Override
            public void onSuccess(SocialPersonalHomepageBean socialPersonalHomepageBean) {
                Hawk.put(SPKey.SP_KEY_USER_PERFECTTATIO_NUMBER, socialPersonalHomepageBean.getPerfectRatio());
            }

            @Override
            public void onError(String errMsg) {

            }
        });
        finish();
    }

    @Override
    public void onSaveFailed(String msg) {
        hideLoadingDialog();
        ToastUtils.showShort(msg);
    }

    @Override
    public void onUpdateAttributeSuccess(EditPicutreResultBean data) {
        hideLoadingDialog();
        ToastUtils.showShort("操作成功");
    }

    @Override
    public void onUpdateAttributeFailed(String msg) {
        hideLoadingDialog();
        ToastUtils.showShort(msg);
    }

    /**
     * 上传头像至阿里云服务器
     *
     * @param fileName 本地图片文件路径
     */
    @SuppressLint("AutoDispose")
    private void uploadAvatar(String fileName) {
        showLoadingDialog();
        Disposable disposable = Observable
                .create((ObservableOnSubscribe<String>) emitter -> {
                    File file = new File(fileName);
                    OssHelper.getOss(mActivity).putObject(OssHelper.getPutObjectRequest(OssHelper.IMAGE + file.getName(), file.getPath()));
                    String url = OssHelper.getOssPrefixUrl(OssHelper.IMAGE, file.getName());
                    emitter.onNext(url);

                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe((String s) -> {
                    hideLoadingDialog();
                    //上传成功
                    saveData(s);
                }, Throwable::printStackTrace);
    }

    /**
     * 上传语音至阿里云
     *
     * @param fileName 音频文件本都路径
     */
    @SuppressLint("AutoDispose")
    private void uploadAudio(String fileName) {
        showLoadingDialog();
        Disposable disposable = Observable
                .create((ObservableOnSubscribe<String>) emitter -> {
                    File file = new File(fileName);
                    OssHelper.getOss(mActivity).putObject(OssHelper.getPutObjectRequest(OssHelper.IMAGE + file.getName(), file.getPath()));
                    String url = OssHelper.getOssPrefixUrl(OssHelper.IMAGE, file.getName());
                    emitter.onNext(url);

                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe((String s) -> {
                    hideLoadingDialog();
                    //上传成功
                    saveAudio(s);
                }, Throwable::printStackTrace);
    }

    /**
     * 上传封面至阿里云
     */
    @SuppressLint({"AutoDispose", "CheckResult"})
    private void uploadPictures() {
        len = 0;
        Observable.fromIterable(images)
                .observeOn(Schedulers.io())
                .map(localMedia -> {
                    File file = new File(localMedia.getCompressPath());
                    OssHelper.getOss(mActivity, true).putObject(OssHelper.getPutObjectRequest(OssHelper.GS_APP_VOICE + file.getName(), file.getPath()));
                    return OssHelper.getOssPrefixUrl(OssHelper.GS_APP_VOICE, file.getName());
                })
                .subscribe(s -> {
                    len++;
                    imageList.add(s);
                    if (len == images.size()) {
                        finishUploadImages(imageList);
                    }
                }, Throwable -> {
//                    Log.e("封面", "上传失败");
//                    runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            ToastUtils.showShort("上传失败请重新上传");
//                        }
//                    });
                });
    }

    /**
     * 上传本地图片完成
     *
     * @param images
     */
    private void finishUploadImages(List<String> images) {
        List<UploadImageBean> uploadImageBeanList = publishEditListAdapter.getData();

        int index = 0;
        for (UploadImageBean uploadImageBean : uploadImageBeanList) {
            if (uploadImageBean.getItemType() == 0 && !uploadImageBean.getPath().startsWith("http")) {
                uploadImageBean.setPath(images.get(index));
                index++;
            }
        }
        updateAttribute(publishEditListAdapter.getData());
    }

    /**
     * 更新音频介绍
     *
     * @param s 音频文件路径
     */
    private void saveAudio(String s) {

        UpdateAttributeRequestBean updateAttributeRequestBean = new UpdateAttributeRequestBean();
        updateAttributeRequestBean.setTagType(6);//语音
        updateAttributeRequestBean.setFileType(3);//音频
        List<UpdateAttributeRequestBean.FilePathBean> filePath = new ArrayList<>();
        UpdateAttributeRequestBean.FilePathBean filePathBean = new UpdateAttributeRequestBean.FilePathBean();
        if (audioId != -1) {
            filePathBean.setId(audioId + "");
        }
        filePathBean.setFilePath(s);
        filePathBean.setFileLength(StringUtils.getMediaDurationMill(s));
        filePath.add(filePathBean);

        updateAttributeRequestBean.setFilePath(filePath);//图片集合
        showLoadingDialog();
        mPresenter.updateAttribute(JSON.toJSONString(updateAttributeRequestBean));
    }

    /**
     * 更新封面
     *
     * @param imageList 封面图片集合
     */
    private void updateAttribute(List<UploadImageBean> imageList) {

        UpdateAttributeRequestBean updateAttributeRequestBean = new UpdateAttributeRequestBean();
        updateAttributeRequestBean.setTagType(1);//封面图
        updateAttributeRequestBean.setFileType(1);//图片
        List<UpdateAttributeRequestBean.FilePathBean> filePath = new ArrayList<>();

        for (UploadImageBean uploadImageBean : imageList) {
            if (uploadImageBean.getItemType() != -1) {
                UpdateAttributeRequestBean.FilePathBean filePathBean = new UpdateAttributeRequestBean.FilePathBean();
                filePathBean.setFilePath(uploadImageBean.getPath());
//                filePathBean.setFileLength(StringUtils.getMediaDuration(uploadImageBean.getPath()));
                filePath.add(filePathBean);
            }
        }

        updateAttributeRequestBean.setFilePath(filePath);//图片集合

        mPresenter.updateAttribute(JSON.toJSONString(updateAttributeRequestBean));
    }

    /**
     * 保存编辑资料
     *
     * @param avatar 头像链接地址
     */
    private void saveData(String avatar) {
        String mapLng = null;
        String mapLat = null;
        if (Hawk.contains(SPKey.SP_KEY_USER_ADDRESS_MAP_LNG)) {
            double lng = Hawk.get(SPKey.SP_KEY_USER_ADDRESS_MAP_LNG);
            double lat = Hawk.get(SPKey.SP_KEY_USER_ADDRESS_MAP_LAT);
            mapLng = lng + "";
            mapLat = lat + "";
        }
        if (personalAddNikeName.getText().toString().trim().length() == 0) {
            ToastUtils.showShort("昵称不能为空");
            return;
        }
        showLoadingDialog();
        mPresenter.saveGaUserExt(null, null, avatar, residence, null, null, null, personalAddNikeName.getText().toString().trim(), null, null, null, null, null, null, null, sex + "", null, personalAddPersonalized.getText().toString().trim(), null, null, null, null, null, mapLng, mapLat, age + "", null, birthday, birthdayShow + "", marriage, marriageShow + "", sexual, sexualShow + "", friendsIntention, loveType, residenceCode, hometown, hometownCode, userProfile);

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1001) {
            //方式一校验
            boolean isHasAudioPermission = CheckAudioPermission.isHasPermission(this);
            Log.i(TAG, "申请权限完毕,当前录音权限:" + isHasAudioPermission);
            //方式二校验
            int result = 0;
            for (int i = 0; i < grantResults.length; i++) {
                if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                    result++;
                }
            }
            if (result != permissions.length) {
                //没有权限
                showBottomToast("请先允许录音权限,请前往设置界面打开录音权限!");
                Log.i(TAG, "onRequestPermissionsResult: 申请权限完毕,当前录音权限:false");
                return;
            }

        }
    }

}
